/****************************************************************************
**
** Copyright (C) 2012 Denis Shienkov <denis.shienkov@gmail.com>
** Copyright (C) 2012 Laszlo Papp <lpapp@kde.org>
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtSerialPort module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "settingsdialog.h"
#include "ui_settingsdialog.h"

#include <QtSerialPort/QSerialPortInfo>
#include <QRegExp>
#include <QLineEdit>
#include <QSettings>
#include <QMessageBox>
#include <QNetworkConfigurationManager>
#include <QHostInfo>
#include <QHostAddress>
#include <QNetworkInterface>
#include <QNetworkAddressEntry>
#include <QFile>

QT_USE_NAMESPACE

static const char blankString[] = QT_TRANSLATE_NOOP("SettingsDialog", "N/A");

SettingsDialog::SettingsDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SettingsDialog)
{
    ui->setupUi(this);
    // 移除标题栏
    this->setWindowFlags(Qt::FramelessWindowHint);

    connect(ui->btnSave, SIGNAL(clicked()), this, SLOT(save()));
    connect(ui->btnClose, SIGNAL(clicked()), this, SLOT(close()));
}

void SettingsDialog::initialInfo(){
    initialUI();
    initialIniConfig();
    initialNet();
}

void SettingsDialog::initialUI(){
    ui->txtVersion->setEnabled(false);
    ui->txtName->setEnabled(false);
    ui->txtNumber->setEnabled(false);
    ui->txtIP->setEnabled(false);
    ui->txtVersion->setText("*");
    ui->txtName->setText("*");
    ui->txtNumber->setText("*");
    ui->txtDevice->setText("*");
    ui->txtIP->setText("*");
    ui->txtMac->setText("*");
    ui->txtMask->setText("*");
    ui->txtBrod->setText("*");
}

void SettingsDialog::initialNet(){
    QString hostname = QHostInfo::localHostName();
    ui->txtDevice->setText(hostname);
    foreach (QNetworkInterface netInterface, QNetworkInterface::allInterfaces()){
        //MAC地址
        ui->txtMac->setText(netInterface.hardwareAddress());
        QList<QNetworkAddressEntry> entryList = netInterface.addressEntries();
        //遍历每一个IP地址(每个包含一个IP地址，一个子网掩码和一个广播地址)
        foreach(QNetworkAddressEntry entry, entryList) {
            //IP地址
            ui->txtIP->setText(entry.ip().toString());
            //子网掩码
            ui->txtMask->setText(entry.netmask().toString());
            //广播地址
            ui->txtBrod->setText(entry.broadcast().toString());
        }
    }

}

void SettingsDialog::initialIniConfig(){
    // 配置文件路径
    QString dir = QCoreApplication::applicationDirPath();
    QString filename = dir + "/EPOS.ini";
    QSettings settings(filename, QSettings::IniFormat);
    settings.beginGroup("server");
    ui->txtServer->setText(settings.value("serveruri").toString());
    ui->txtPort->setText(settings.value("serverport").toString());
    settings.endGroup();

    settings.beginGroup("system");
    ui->txtVersion->setText(settings.value("version").toString());
    ui->txtName->setText(settings.value("name").toString());
    ui->txtUptime->setText(settings.value("updatetime").toString());
    settings.endGroup();

    settings.beginGroup("machine");
    ui->txtNumber->setText(settings.value("id").toString());
    settings.endGroup();

    settings.beginGroup("wifi");
    ui->txtWifi->setText(settings.value("name").toString());
    ui->txtPassword->setText(settings.value("password").toString());
    settings.endGroup();
}

void SettingsDialog::save(){

    QString server = ui->txtServer->text();
    QString port = ui->txtPort->text();
    QString wifi = ui->txtWifi->text();
    QString password= ui->txtPassword->text();
    QString uptime = ui->txtUptime->text();

    QRegExp IPRegexp("((25[0-5]|2[0-4]\\d|[1]{1}\\d{1}\\d{1}|[1-9]{1}\\d{1}|\\d{1})($|(?!\\.$)\\.)){4}");
    if(!IPRegexp.exactMatch(server)){
        QRegExp DomRegexp("[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+.?");
        if(!DomRegexp.exactMatch(server)){
            QMessageBox::about(this, "提示", "服务器地址无效");
            return;
        }
    }

    if(!isNumber(port)){
        QMessageBox::about(this, "提示", "端口无效");
        return;
    }

    if(!isEmpty(wifi)){
        QMessageBox::about(this, "提示", "Wifi名称不能为空");
        return;
    }

    if(!isEmpty(password)){
        QMessageBox::about(this, "提示", "Wifi密码不能为空");
        return;
    }

    if(!isEmpty(uptime)){
        QMessageBox::about(this, "提示", "更新时间无效");
        return;
    }

    QString dir = QCoreApplication::applicationDirPath();
    QString filename = dir + "/EPOS.ini";
    QSettings settings(filename, QSettings::IniFormat);

    settings.beginGroup("server");
    settings.setValue("serveruri", server);
    settings.setValue("serverport", port);
    settings.endGroup();

    settings.beginGroup("wifi");
    settings.setValue("name", wifi);
    settings.setValue("password", password);
    settings.endGroup();

    settings.beginGroup("system");
    settings.setValue("updatetime", uptime);
    settings.endGroup();

    settings.sync();
    QMessageBox::about(this, "提示", "保存配置信息成功");
    initialNet();
    initialIniConfig();
}

bool SettingsDialog::isEmpty(QString string){
    if(string.isNull() || string.isEmpty() || string.length() < 1 ||
    string.trimmed().length() < 1){
        return false;
    }
    return true;
}

bool SettingsDialog::isNumber(QString string){
    if(!isEmpty(string)) return false;
    for(int i = 0; i < string.length(); i++){
        if(string.at(i) < '0' || string.at(i) > '9') return false;
    }
    return true;
}

SettingsDialog::~SettingsDialog()
{
    delete ui;
}
